const { Controller } = require('egg');

class BlogController extends Controller {
    /**
     * 发表博客
     */
    async create() {
        // 解构参数
        const { title, content } = this.ctx.request.body;
        // console.log('BlogController', this.ctx.user);
        // 非空校验
        if (!title || !content) {
            this.ctx.body = {
                code: 400,
                message: '缺少必需参数',
            };
            return;
        }
        // 调用 service 层，保存博客
        let res = await this.ctx.service.blog.create({
            uid: this.ctx.user.id,
            title,
            content,
        });
        // {
        //     affectedRows: 1,
        //     insertId: 1
        // }
        // 判断是否插入成功
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: '博客发表失败，请稍后再试！',
            };
            return;
        }
        // 返回添加成功响应
        this.ctx.body = {
            code: 201,
            message: '博客发表成功',
        };
    }

    /**
     * 博客列表
     */
    async index() {
        let res = await this.ctx.service.blog.readList();
        this.ctx.body = {
            code: 200,
            data: res,
            message: '获取博客列表成功',
        };
    }

    async detail() {}

    async update() {}
}

module.exports = BlogController;
